//
//  BaiKeDetailVC.m
//  BaseProject
//
//  Created by mac on 2020/12/23.
//  Copyright © 2020 王洋. All rights reserved.
//

#import "BaiKeDetailVC.h"
#import <WebKit/WebKit.h>
#import "BaiKeSubListModel.h"
@interface BaiKeDetailVC ()<WKNavigationDelegate,WKUIDelegate>
@property(nonatomic,strong)UIScrollView *mainView;
@property(nonatomic,strong)UILabel *titleLab;
@property(nonatomic,strong)UILabel *threeNameLab;
@property(nonatomic,strong)UILabel *timeLab;
@property(nonatomic,strong)WKWebView *webView;
@property(nonatomic,strong)UIActivityIndicatorView *indicatorView;
@property(nonatomic,strong)UIProgressView *progressView;
@property(nonatomic,strong)UIButton *shareButton;
@end

@implementation BaiKeDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createProperty];
    [self createUI];
    
}
- (void)dealloc
{
    NSLog(@"BaiKeDetailVC ---dealloc");
}
- (void)createProperty
{
    
}
- (void)createUI
{
    [self createNaviBarWithTitle:@"文章详情" backButtonBlock:nil];
    [self shareButton];
    self.titleLab.text = self.listModel.title;
    self.threeNameLab.text = self.listModel.threeName;
    self.timeLab.text = self.listModel.createTime;
    [self.webView loadHTMLString:[self reSizeImageWithHTML:self.listModel.detail] baseURL:nil];
    //[self.webView loadRequest:[NSURLRequest requestWithURL:@"https://www.baidu.com".wppURL]];
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    [self.indicatorView startAnimating];
    //frame
    CGFloat titleHeight = [self.titleLab.text sizeWithMaxWidth:self.titleLab.width andFont:self.titleLab.font].height;
    self.titleLab.height = titleHeight;
    CGFloat threeNameWidth = [self.threeNameLab.text sizeWithFont:self.threeNameLab.font].width + 26*ADAPTER_WIDTH;
    self.threeNameLab.width = threeNameWidth;
    self.threeNameLab.top = self.titleLab.bottom + 16*ADAPTER_WIDTH;
    self.timeLab.centerY = self.threeNameLab.centerY;
    self.webView.top = self.threeNameLab.bottom + 16*ADAPTER_WIDTH;
    self.webView.height = self.mainView.height - self.webView.top;
}
- (NSString *)reSizeImageWithHTML:(NSString *)html
{
    return [NSString stringWithFormat:@"<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0'><meta name='apple-mobile-web-app-capable' content='yes'><meta name='apple-mobile-web-app-status-bar-style' content='black'><meta name='format-detection' content='telephone=no'><style type='text/css'>img{width:%@}*{padding:0, margin:0}*{white-space: pre-line}</style>%@",@"100%",html];
}
#pragma mark - WebViewDelegate
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    if ([self.progressView isDescendantOfView:self.webView]) {
        self.progressView.hidden = YES;
        self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
    }
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    WK(weakSelf)
    [self.indicatorView stopAnimating];
    [webView evaluateJavaScript:@"document.body.offsetHeight;" completionHandler:^(id _Nullable obj, NSError * _Nullable error) {
        //weakSelf.webView.height = [obj floatValue] + 10;
        //weakSelf.mainView.contentSize = CGSizeMake(0, MAX(self.mainView.height + 1, weakSelf.webView.bottom + kBottomSafeHeight + 10*ADAPTER_WIDTH));
        NSLog(@"%f",[obj floatValue]);
    }];
}
#pragma mark - 监听
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        NSLog(@"%f",self.webView.estimatedProgress);
        self.progressView.hidden = YES;
        self.progressView.progress = self.webView.estimatedProgress;
        if (self.progressView.progress == 1) {
            WK(weakSelf)
            [UIView animateWithDuration:0.25f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
                weakSelf.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.4f);
            } completion:^(BOOL finished) {
                weakSelf.progressView.hidden = YES;
            }];
        }
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}
#pragma mark - click
- (void)clickShareButton:sender
{
    CommonShareModel *model = [[CommonShareModel alloc] init];
    model.url = [NSString stringWithFormat:@"%@%@?sweId=%@&replyUserId=%@&myCode=%@",BA_GlobalH5_Domain,@"/articleDetailShare",self.listModel.sweId,[TTUserModel sharedObject].userId,[TTUserModel sharedObject].myCode];
    model.title = self.listModel.title;
    model.content = self.listModel.briefIntroduction;
    model.image = [UIImage imageNamed:@"ba_logo"];
    [[TT_ShareManager share] callShareViewWithModel:model];
    
}
#pragma mark - lazy懒加载
- (WKWebView *)webView
{
    if (!_webView) {
        WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
        WKUserContentController *userController = [[WKUserContentController alloc] init];
        configuration.userContentController = userController;
        WKWebView *view = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - kTopHeight) configuration:configuration];
        [self.mainView addSubview:view];
        view.navigationDelegate = self;
        view.UIDelegate = self;
        view.backgroundColor = UIColorHex(0xf1f1f1);
        _webView = view;
    }
    return _webView;
}
- (UIProgressView *)progressView
{
    if (!_progressView) {
        UIProgressView *view = [[UIProgressView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 0.5)];
        view.backgroundColor = RedColor;
        view.progressTintColor = rgba(255, 66, 66, 1);
        view.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
        [self.webView addSubview:view];
        view.hidden = YES;
        _progressView = view;
    }
    return _progressView;
}
- (UIActivityIndicatorView *)indicatorView {
    if (!_indicatorView) {
        _indicatorView = [[UIActivityIndicatorView alloc]init];
        _indicatorView.hidesWhenStopped = YES;
        _indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
        [self.webView addSubview:_indicatorView];
        [_indicatorView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(0);
        }];
    }
    return _indicatorView;
}
- (UIScrollView *)mainView
{
    if (!_mainView) {
        UIScrollView *view = [[UIScrollView alloc]initWithFrame:CGRectMake(0, kTopHeight, WIDTH, HEIGHT - kTopHeight)];
        [self.view addSubview:view];
        view.backgroundColor = WhiteColor;
        if (@available(iOS 11.0, *))
        {
            view.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        else
        {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        _mainView = view;
    }
    return _mainView;
}
- (UILabel *)titleLab
{
    if (!_titleLab) {
        UILabel *lab = [[UILabel alloc]init];
        [self.mainView addSubview:lab];
        lab.font = [UIFont systemFontOfSize:20*ADAPTER_WIDTH weight:UIFontWeightBold];
        lab.textColor = kColor51;
        lab.textAlignment = NSTextAlignmentLeft;
        lab.numberOfLines = 0;
        lab.frame = CGRectMake(14*ADAPTER_WIDTH, 10*ADAPTER_WIDTH, WIDTH - 28*ADAPTER_WIDTH, 0);
        _titleLab = lab;
    }
    return _titleLab;
}
- (UILabel *)threeNameLab
{
    if (!_threeNameLab) {
        UILabel *lab = [[UILabel alloc]init];
        [self.mainView addSubview:lab];
        lab.font = [UIFont systemFontOfSize:12*ADAPTER_WIDTH weight:UIFontWeightRegular];
        lab.textColor = rgba(255, 66, 66, 1);
        lab.textAlignment = NSTextAlignmentCenter;
        lab.numberOfLines = 1;
        lab.frame = CGRectMake(14*ADAPTER_WIDTH, 0, 0, 24*ADAPTER_WIDTH);
        lab.backgroundColor = rgba(255, 66, 66, 0.08);
        lab.layer.cornerRadius = 12*ADAPTER_WIDTH;
        lab.layer.masksToBounds = YES;
        _threeNameLab = lab;
    }
    return _threeNameLab;
}
- (UILabel *)timeLab
{
    if (!_timeLab) {
        UILabel *lab = [[UILabel alloc]init];
        [self.mainView addSubview:lab];
        lab.font = [UIFont systemFontOfSize:12*ADAPTER_WIDTH weight:UIFontWeightRegular];
        lab.textColor = kColor153;
        lab.textAlignment = NSTextAlignmentRight;
        lab.numberOfLines = 1;
        lab.frame = CGRectMake(WIDTH - 214*ADAPTER_WIDTH, 0, 200*ADAPTER_WIDTH, 17*ADAPTER_WIDTH);
        _timeLab = lab;
    }
    return _timeLab;
}
- (UIButton *)shareButton
{
    if (!_shareButton) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.naviBarView addSubview:button];
        [button setImage:[UIImage imageNamed:@"input_share"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(clickShareButton:) forControlEvents:UIControlEventTouchUpInside];
        button.frame = CGRectMake(WIDTH - 50*ADAPTER_WIDTH, 41*ADAPTER_WIDTH, 50*ADAPTER_WIDTH, 41*ADAPTER_WIDTH);
        button.imageEdgeInsets = UIEdgeInsetsMake(10*ADAPTER_WIDTH, 14*ADAPTER_WIDTH, 10*ADAPTER_WIDTH, 14*ADAPTER_WIDTH);
        button.centerY = self.naviBarTitleLab.centerY;
        _shareButton = button;
    }
    return _shareButton;
}
@end
